package com.astersoft.lib.util;

/*
 * Copyright 2012 AsterSoft personal developer - Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

import java.util.concurrent.TimeUnit;

/**
 * ASChrono
 * 
 * Chronometer class that can be used for the time-lapse
 * of execution
 * 
 * @author dario.durzo
 * @version 0.1
 * @created.date 2009.08.26
 */
public class ASChrono {
	// internal times
	private static long startTime;
	private static long endTime;

	public static void startChrono() {
		startTime = System.currentTimeMillis();
		endTime = 0L;
	}

	public static void stopChrono() {
		endTime = System.currentTimeMillis();
		if(startTime == 0L)
			endTime = 0L;
	}

	/**
	 * Get formatted elapsed
	 * 
	 * @return
	 */
	public static String getElapsed() {
		if(startTime == 0L || endTime == 0L){
			throw new IllegalArgumentException("No time setted");
		}
		long elapsed = endTime - startTime;

		if(elapsed < 0)
			throw new IllegalArgumentException("Time setting wrong [endTime < startTime]");

		return millisToShortDHMS(elapsed);
	}

	
	/**
	 * converts time (in milliseconds) to human-readable format
	 * "<dd:>hh:mm:ss"
	 * 
	 * @param duration
	 * @return
	 */
	public static String millisToShortDHMS(long duration) {
		String res = "";
		long days  = TimeUnit.MILLISECONDS.toDays(duration);
		long hours = TimeUnit.MILLISECONDS.toHours(duration)
				- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
		long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
				- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
		long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
				- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
		
		if (days == 0) {
			if(hours == 0){
				res = String.format("%02d:%02d", minutes, seconds);
			} else {
				res = String.format("%02d:%02d:%02d", hours, minutes, seconds);
			}
		} else {
			res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
		}
		return res;
	}
}
